import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/manhua_list_provider.dart';
import 'widget/manhua_list_item.dart';

class ManhuaListScrren extends ConsumerStatefulWidget {
  final String categoryId;
  final int sortBy;
  final String title;

  const ManhuaListScrren({
    super.key,
    required this.categoryId,
    this.sortBy = 1,
    required this.title,
  });

  @override
  ConsumerState<ManhuaListScrren> createState() => _ManhuaListScrrenState();
}

class _ManhuaListScrrenState extends ConsumerState<ManhuaListScrren> {
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      // 距离底部200像素时开始加载更多
      final params = ManhuaListParams(
        categoryId: widget.categoryId,
        sortBy: widget.sortBy,
      );
      ref.read(manhuaListProvider(params).notifier).loadMore();
    }
  }

  @override
  Widget build(BuildContext context) {
    ManhuaListParams params = ManhuaListParams(
      categoryId: widget.categoryId,
      sortBy: widget.sortBy,
    );
    if (widget.title == "Frees") {
      params = ManhuaListParams(
        categoryId: widget.categoryId,
        ChargeStatus: 1,
      );
    }
    final state = ref.watch(manhuaListProvider(params));

    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      appBar: AppBar(
        title: Text(widget.title),
        centerTitle: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: SafeArea(
        child: RefreshIndicator(
          onRefresh: () async {
            await ref.read(manhuaListProvider(params).notifier).refresh();
          },
          child: _buildBody(state, params),
        ),
      ),
    );
  }

  Widget _buildBody(ManhuaListState state, ManhuaListParams params) {
    // 初始加载状态
    if (state.isLoading && state.comics.isEmpty) {
      return const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
        ),
      );
    }

    // 错误状态
    if (state.hasError && state.comics.isEmpty) {
      return _buildErrorWidget(params);
    }

    // 无数据状态
    if (state.comics.isEmpty && !state.isLoading) {
      return _buildEmptyWidget(params);
    }

    // 有数据状态
    return ListView.builder(
      controller: _scrollController,
      itemCount: state.comics.length + (state.hasMore ? 1 : 0),
      itemBuilder: (context, index) {
        // 显示漫画项
        if (index < state.comics.length) {
          return Padding(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 20),
            child: ManhListItem(
              comic: state.comics[index], // 传递漫画数据
            ),
          );
        }

        // 显示加载更多指示器
        if (state.isLoadingMore) {
          return const Padding(
            padding: EdgeInsets.all(16.0),
            child: Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),
          );
        }

        // 没有更多数据
        return const Padding(
          padding: EdgeInsets.all(16.0),
          child: Center(
            child: Text(
              '没有更多内容了',
              style: TextStyle(color: Colors.grey),
            ),
          ),
        );
      },
    );
  }

  // 错误状态组件
  Widget _buildErrorWidget(ManhuaListParams params) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '加载失败',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[400],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请检查网络连接后重试',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              ref.read(manhuaListProvider(params).notifier).refresh();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
            ),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  // 空数据状态组件
  Widget _buildEmptyWidget(ManhuaListParams params) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.inbox_outlined,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无内容',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[400],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '这里还没有漫画，请稍后再来看看',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              ref.read(manhuaListProvider(params).notifier).refresh();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
            ),
            child: const Text('刷新'),
          ),
        ],
      ),
    );
  }
}
